package com.code.generation.utils;

import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

/**
 * @ProjectName: codegeneration
 * @Package: com.code.generation.utils
 * @Description:
 * @Author: DongJW
 * @CreateDate: 2020/11/29 11:42
 * @Version: 1.0
 */
public class ConfigurationUtils {

    private volatile static Configuration configuration;

    /**
     * 初始化configuration
     * @param templateAbsolutePath 模板文件夹
     * @throws Exception 异常
     */
    public static void init(String templateAbsolutePath) throws Exception {
        if (null==configuration){
            synchronized (ConfigurationUtils.class){
                if (null==configuration){
                    try {
                        configuration = new Configuration(Configuration.getVersion());
                        configuration.setTemplateLoader(new FileTemplateLoader(new File(templateAbsolutePath)));
                    } catch (IOException e) {
                        throw new Exception("初始化configuration出错 "+e.getMessage());
                    }
                }
            }
        }
    }

    /**
     * 生成代码
     * @param tempName 模板名称（\${projectName}\pom.xml）
     * @param outPath 生成文件根目录（D:\MyFils）
     * @param outFileName 字符串模板路径（包层级+文件名）
     * @param dataModel 数据模型
     * @throws Exception 异常
     */
    public static void generatorFile(String tempName, String outPath, String outFileName,Map<String,Object> dataModel)throws Exception{
        //模板处理
        Writer fileWriter = null;
        try {
            //模板
            Template template  = configuration.getTemplate(tempName);
            //创建文件
            File fileOutPath = FileUtils.createFile(outPath, outFileName);
            fileWriter =new FileWriter(fileOutPath);
            //6.文件输出（在文件中将内容替换为数据模型的数据）
            template.process(dataModel, fileWriter);
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }finally {
            if (null!=fileWriter){
                fileWriter.close();
            }
        }
    }

    /**
     * 生成字符串模板路径
     * @param templateString 字符串模板
     * @param dataModel 模板数据
     * @return 字符串模板路径
     * @throws Exception 异常
     */
    public static String processStringTemplate(String templateString,Map<String,Object> dataModel)throws Exception {
        StringWriter out = new StringWriter();
        Template template = new Template("template",new StringReader(templateString),configuration);
        template.process(dataModel, out);
        return out.toString();
    }
}
